package net.atomarrow.domains;

import java.util.List;

import net.atomarrow.configs.DbConfig;
import net.atomarrow.db.orm.OrmContext;
import net.atomarrow.ioc.ApplicationContext;
import net.atomarrow.services.IService;
import net.atomarrow.services.Service;


public class DomainUtil {

    public static String getSingleTableName(Domain domain){
        return domain.getClass().getSimpleName();
    }
    public static String getMultiTableName(Domain domain,int id){
        return getMultiTableName(domain.getClass().getSimpleName(), id);
    }
    public static String getMultiTableName(String domainName,int id){
        return getMappingName(domainName)+"_"+id;
    }
    
    public static boolean isSingleTable(String domainName){
        return !domainName.contains("_");
    }
    public static boolean isMultiTable(String domainName){
        return domainName.contains("_");
    }
    
    public static String getMappingName(String domainName){
        int sIndex = domainName.indexOf("_");
        if (sIndex != -1) {
           return domainName.substring(0, sIndex);
        } else {
            return domainName;
        }
    }
    /**
     * 所有不分表的表进行生成
     */
    public static void generateAllSingleTable(){
	    ApplicationContext.load(new Service());
	    IService service = ApplicationContext.get(Service.class);
	    DbConfig config = ApplicationContext.get(DbConfig.class);
	    DbMaker dm=new DbMaker(DbConfig.getDatabaseName());
	    List<String> domainNames = OrmContext.getSingleTableDomainNames();
	    for(String domainName:domainNames){
	        dm.makeTable(domainName,OrmContext.getDomainClass(domainName), service);
	    }
    }
    
    /**
     * 所有分表的表进行生成
     * @param id
     */
	public static void generateAllMultiTable(int id){
	    ApplicationContext.load(new Service());
	    IService service = ApplicationContext.get(Service.class);
	    DbConfig config = ApplicationContext.get(DbConfig.class);
	    DbMaker dm=new DbMaker(DbConfig.getDatabaseName());
	    List<String> domainNames = OrmContext.getMultipleTableDomainNames();
	    for(String domainName:domainNames){
	    	 dm.makeTable(DomainUtil.getMultiTableName(domainName, id),OrmContext.getDomainClass(domainName), service);
	    }
    }
}
